package server;

import java.util.HashMap;
import java.util.Map;

/**
 * a poll, The class is not finished Some basic pool creation, still not
 * possible to give the coices
 *
 */
public class Poll {

    private Map<VoterIDInterface, VoteInterface> votes = new HashMap<>();
    private boolean started = false;
    private boolean paused = false;
    private boolean stoped = false;
    private long id;
    private String[] options;
    private String emailAddress;
    private int[] stats;

    public Poll(long id, String[] _options, String emailAddress) {
        this.id = id;
        this.options = _options;
        this.emailAddress = emailAddress;
        stats = new int[options.length];
    }

    public synchronized boolean addVote(VoteInterface vote, StringBuilder errorMessage) {
        if (!this.isEnabled()) {
            errorMessage.append("Pool Not Enabled");
            return false;
        }
        if (stats.length <= vote.getVoteChoice()) {
            errorMessage.append("Vote choice incorrect");
            return false;
        }

        VoterIDInterface voterId = vote.getVoterId();
        VoteInterface v = votes.get(voterId);
        if (v == null) {
            votes.put(voterId, vote);
            stats[vote.getVoteChoice()]++;
            return true;
        }

        if (v.getVoteChoice() != vote.getVoteChoice()) {
            stats[v.getVoteChoice()]--;
            stats[vote.getVoteChoice()]++;
            return true;
        }

        return true;
    }

    public long getId() {
        return id;
    }

    public synchronized boolean isEnabled() {
        return started && !paused && !stoped;
    }

    public synchronized boolean start() {
        if (!this.started) {
            this.started = true;
            return true;
        }
        return false;
    }

    public synchronized boolean stop() {
        if (this.started && !this.stoped) {
            this.results();
            this.votes = null;
            this.stoped = true;
            return true;
        }
        return false;
    }

    public synchronized boolean pause() {
        if (this.started && !this.paused && !this.stoped) {
            this.paused = true;
            return true;
        }
        return false;
    }

    public synchronized boolean resume() {
        if (this.started && this.paused && !this.stoped) {
            this.paused = false;
            return true;
        }
        return false;
    }

    public synchronized boolean clearResults() {
        this.votes = new HashMap<>();
        return true;
    }

    private boolean results() {
        return true;
        //throw new UnsupportedOperationException("Not yet implemented");
    }

    public synchronized int[] getStats() {
        return stats.clone();
    }
}
